//
//  AutoDownloadCheckingOperator.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-4.
//
//

#import "AutoDownloadCheckingOperator.h"
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import "CubeModuleAutoSaveParser.h"
#import "DependsOnParser.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import "CubeModule.h"
#import <chameleon-ios-sdk/CApplication.h>
#import <chameleon-ios-sdk/CubeModel.h>


@interface AutoDownloadCheckingOperator()

//获取已检测自动下载的模块列表
-(NSMutableArray*)loadLocalCheckedList;

//保存已检测自动下载的模块列表
-(void)saveLocalCheckedList:(NSArray*)array;


//检测自动下载
-(BOOL)checkAutoDownloaded;

//检测自动更新
-(void)checkAutoUpdateed;

//把已检测过的模块保存入本地
-(void)saveCheckedAutoDownloadModuleInCache:(NSArray*)uninstallModules;

@end

@implementation AutoDownloadCheckingOperator

-(id)init{
    self=[super init];
    
    if(self){
        downloadModels=[[NSMutableArray alloc] initWithCapacity:1];
        self.dependDownloadlist=[[NSMutableArray alloc] initWithCapacity:2];
        self.dependUpdatelist=[[NSMutableArray alloc] initWithCapacity:2];
    }
    return self;
}

-(void)start{
    if(![self checkAutoDownloaded]){
        [self checkAutoUpdateed];
    }
}

-(NSArray*)loadLocalCheckedList{
    CubeModuleAutoSaveParser* parser=[[CubeModuleAutoSaveParser alloc] init];
    
    
    NSString* username=[DataCenter defaultCenter].username;

    NSString* file=[IsolatedStorageFile loadAutoSaveFile:username];
    NSData* data=[[NSData alloc] initWithContentsOfFile:file];
    [parser parse:data];
    NSMutableArray* array=[parser getResult];
    return array;
}

-(void)saveLocalCheckedList:(NSArray*)array{
    NSString* str=[CubeModuleAutoSaveParser parserJSONFromArray:array];
    NSString* username=[DataCenter defaultCenter].username;
    
    NSString* file=[IsolatedStorageFile loadAutoSaveFile:username];
    [str writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
}


-(void)clear{
    [downloadModels removeAllObjects];
    [self.dependDownloadlist removeAllObjects];
    [self.dependUpdatelist removeAllObjects];
}

-(void)saveCheckedAutoDownloadModuleInCache:(NSArray*)uninstallModules{
    @autoreleasepool {
        //这个方法是将已经检测过自动更新过的模块记录去本地文件
        NSMutableArray* autoSaveCubeModules = [self loadLocalCheckedList];
        if (autoSaveCubeModules == nil)
            autoSaveCubeModules = [[NSMutableArray alloc] initWithCapacity:1];
        
        
        for (CubeModel* cubeModel in uninstallModules){
            
            /*
             张国东
             对自动下载模块，增加权限判断
             */
            if (cubeModel.autoDownload  && [[DataCenter defaultCenter] priviligeGetModuleByIdentifier:cubeModel.identifier]){
                BOOL canDownloaded = YES;
                for (NSString* autoSaveIdentifier in autoSaveCubeModules){
                    if ([autoSaveIdentifier isEqualToString:cubeModel.identifier]){
                        canDownloaded = NO;
                        break;
                    }
                }
                
                if (canDownloaded){
                    [autoSaveCubeModules addObject:cubeModel.identifier];
                    [downloadModels addObject:cubeModel];
                }
            }
        }
        [self saveLocalCheckedList:autoSaveCubeModules];
        
    }
}

-(BOOL)checkAutoDownloaded{
    [downloadModels removeAllObjects];
//    self.autoDownloadedCount = 0;
    BOOL hasAutoDownloaded = NO;
    
    NSArray* uninstallModules=[DataCenter defaultCenter].uninstallModules;
    if ([uninstallModules count] > 0){

        [self saveCheckedAutoDownloadModuleInCache:uninstallModules];
        
        
        if ([downloadModels count] > 0){
            
            self.autoDownloadedCount=[downloadModels count];

            hasAutoDownloaded = YES;
            
            NSMutableString* message=[[NSMutableString alloc] initWithCapacity:1];
            [message appendString:@"检测到有以下模块需要下载:\n"];
            
            for (CubeModel* cubeModel in downloadModels){
                [message appendFormat:@"%@\n",cubeModel.name];
            }
            
            if([self.delegate respondsToSelector:@selector(autoSaveDidShowAutoDownloading:message:)])
                [self.delegate autoSaveDidShowAutoDownloading:self message:message];
        }
    }
    return hasAutoDownloaded;
    
}

-(void)checkAutoUpdateed{
    [downloadModels removeAllObjects];
    //self.autoDownloadedCount=0;
    NSArray* updatableModules=[DataCenter defaultCenter].updatableModules;

    if ([updatableModules count] > 0){
        self.autoDownloadedCount=[updatableModules count];

        NSMutableString* message=nil;
        
        

        for (CubeModel* cubeModel in updatableModules){
            /*
             张国东
             对自动下载模块，增加权限判断
             */
            if([[DataCenter defaultCenter] priviligeGetModuleByIdentifier:cubeModel.identifier]){
                if(message==nil){
                    message=[[NSMutableString alloc] initWithCapacity:1];
                    [message appendString:@"检测到有以下模块需要更新:\n"];
                }
                
                [message appendFormat:@"%@\n",cubeModel.name];
            
                [downloadModels addObject:cubeModel];
            }

        }
        
        if([message length]>1 && [self.delegate respondsToSelector:@selector(autoSaveDidShowUpdating:message:)])
            [self.delegate autoSaveDidShowUpdating:self message:message];

        
    }
}

-(NSArray*)downloadModels{
    return downloadModels;
}

-(NSArray*)dependsList:(NSString*)identifier{
    
    NSString* file = [IsolatedStorageFile dependencieModuleFile:identifier];
    NSData* data=[[NSData alloc] initWithContentsOfFile:file];
    DependsOnParser* parser=[[DependsOnParser alloc] init];
    [parser parse:data];
    NSArray* dependsOnModule=[parser getResult];
    return dependsOnModule;
}


@end
